<template>
  <grid title="用户管理">
    <el-form inline
             style="width: 100%; text-align: left"
             label-width="60px"
             @submit.native.prevent="onSubmit"
             @reset.native.prevent="onReset"
             size="small">
      <el-form-item label="账号">
        <el-input v-model="query.q"
                  placeholder="请输入关键词"
                  clearable></el-input>
      </el-form-item>

      <el-form-item label="账号状态"
                    label-width="80px">
        <el-select v-model="query.status">
          <el-option label="全部"
                     value="all"></el-option>
          <el-option label="正常"
                     value="up"></el-option>
          <el-option label="禁用"
                     value="down"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary"
                   native-type="submit">筛选</el-button>
        <el-button native-type="reset">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right"
                    v-if="user.is_super">
        <el-button type="primary"
                   @click="addUser">新建用户</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list"
              border
              :resizable="false"
              stripe>
      <el-table-column type="index"
                       label="编号"
                       width="60"
                       align="center"></el-table-column>
      <el-table-column prop="avatar"
                       label="头像"
                       width="80"
                       align="center">
        <template slot-scope="scope">
          <el-avatar size="medium"
                     :src="scope.row.avatar.url"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name"
                       label="账号">
      </el-table-column>
      <el-table-column prop="nick_name"
                       label="昵称">
      </el-table-column>
      <el-table-column prop="status"
                       label="账号状态">
        <template slot-scope="scope">
          <template v-if="scope.row.is_unusual">
            <el-tag type="danger"
                    v-if="scope.row.is_disabled">禁用</el-tag>
            <el-tag type="danger"
                    v-if="scope.row.is_muted">禁言</el-tag>
          </template>
          <el-tag v-else>正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status"
                       label="身份">
        <template slot-scope="scope">
          <template v-if="scope.row.roles">
            <el-tag size="small"
                    v-for="(role,index) in scope.row.roles"
                    :key="index">{{role}}</el-tag>
          </template>
          <template v-else>
            无
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="website"
                       label="网站"
                       show-overflow-tooltip>
        <template slot-scope="scope">
          <el-link type="primary"
                   :href="scope.row.website"
                   target="_blank">{{scope.row.website}}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="active_at"
                       label="最后活跃时间">
        <template slot-scope="scope">
          {{scope.row.active_at | timeFilter }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at"
                       label="创建时间">
        <template slot-scope="scope">
          {{scope.row.created_at | timeFilter }}
        </template>
      </el-table-column>
      <el-table-column fixed="right"
                       label="操作"
                       width="240">
        <template slot-scope="scope">
          <el-button type="primary"
                     @click="view(scope.row.id)"
                     size="small"
                     icon="el-icon-view"></el-button>
          <el-button type="warning"
                     @click="editRow(scope.row.id)"
                     size="small"
                     icon="el-icon-edit"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination layout="total, prev, pager, next"
                   background
                   @current-change="fetch"
                   :current-page.sync="query.page"
                   :page-size="query.limit"
                   hide-on-single-page
                   style="display: flex;justify-content: center;"
                   :total="total">
    </el-pagination>
    <el-dialog :title="form.id ? '修改用户' : '新增用户'"
               :visible.sync="dialogVisible"
               width="650px"
               :show-close="false"
               center>
      <el-form ref="dialogForm"
               :model="form"
               label-width="120px"
               :rules="rules"
               width="500px">
        <el-form-item label="账号"
                      prop="name">
          <el-input v-model="form.name"
                    :disabled="!isSuper"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址"
                      prop="email">
          <el-input v-model="form.email"
                    :disabled="!isSuper"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="昵称"
                      prop="nick_name">
          <el-input v-model="form.nick_name"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传头像"
                      prop="icon">
          <image-input type="avatar"
                       v-model="form.avatar"></image-input>
          <span style="color: #999;">注：建议上传尺寸60*60的 PNG图</span>
        </el-form-item>
        <el-form-item label="网址"
                      prop="website">
          <el-input v-model="form.website"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="个人简介"
                      prop="signature">
          <el-input v-model="form.signature"
                    autocomplete="off"
                    type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="是否管理员"
                      v-if="isSuper">
          <el-switch v-model="form.is_admin"
                     active-text="管理员">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="onDialogSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <user-info ref="userInfo"></user-info>
  </grid>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import listMixin from '@/mixin/list'
import imageInput from '@/components/image-input'
import { fetchView, store, edit, authority } from './api'
import userInfo from '@/components/common/user-info'

export default {
  title: '用户管理',
  data () {
    return {
      query: {
        limit: 12,
        page: 1,
        q: undefined,
        status: 'all'
      },
      dialogVisible: false,
      form: {},
      formDefault: {
        id: undefined,
        name: '',
        nick_name: '',
        avatar: [],
        website: '',
        signature: '',
        email: '',
        is_admin: false
      },
      rules: {
        name: [
          { required: true, message: '账号不能为空' }
        ],
        email: [
          { required: true, message: '邮箱不能为空' }
        ]
      }
    }
  },
  components: {
    imageInput, userInfo
  },
  mixins: [listMixin],
  async asyncData ({ store, route }) {
    const { query } = route;
    return store.dispatch('user/fetchList', { page: 1, limit: 12 })
  },
  computed: {
    ...mapGetters('user', ['list', 'total']),
    ...mapGetters('login', ['user']),
    isSuper () {
      return this.user.is_super
    }
  },
  methods: {
    ...mapActions('user', ['fetchList']),
    fetch () {
      this.fetchList(this.query)
    },
    async editRow (id) {
      await fetchView(id).then(({ data: { data } }) => {
        this.form = this.filterForm(data)
        this.form.avatar = [this.form.avatar]
      })
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.dialogForm.clearValidate())
    },
    async authority (id, action) {
      await authority(id, { action }).then(({ data: { data } }) => {
        this.$message.success('处理成功')
      })
      this.fetch()
    },
    async view (id) {
      const refresh = await this.$refs.userInfo.open(id)
      refresh && this.fetch()
    },
    addUser () {
      this.form = { ...this.formDefault }
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.dialogForm.clearValidate())
    },
    async onDialogSubmit () {
      await this.$refs.dialogForm.validate()
      const {
        avatar: [{ id, url }],
        ...params
      } = this.form
      params.avatar = {
        id: id,
        url: url
      }
      if (typeof this.form.id === 'number') {
        await edit(this.form.id, params)
      } else {
        await store(params)
      }
      this.$message.success('保存成功')
      this.fetchList(this.query)
      this.dialogVisible = false
    }
  }
}
</script>
